package web;

import java.io.IOException;
import java.io.InputStream;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

 @Controller
 @RequestMapping(value="wyslij.htm")
public class EmailController {
 
    @Autowired
    private JavaMailSender mailSender;
    
    @RequestMapping(method = RequestMethod.POST)
    public String doEmail(HttpServletRequest request,
            final @RequestParam CommonsMultipartFile zalacznik) {
    	
		// takes input from e-mail form
		final String adres = request.getParameter("adres");
		final String temat = request.getParameter("temat");
		final String tresc = request.getParameter("tresc");
         
		 mailSender.send(new MimeMessagePreparator() {
			 
	            @Override
	            public void prepare(MimeMessage mimeMessage) throws Exception {
	                MimeMessageHelper messageHelper = new MimeMessageHelper(
	                        mimeMessage, true, "UTF-8");
	                messageHelper.setTo(adres);
	                messageHelper.setSubject(temat);
	                messageHelper.setText(tresc);
	                 
	                // determines if there is an upload file, attach it to the e-mail
	                String nazwaZalacznika = zalacznik.getOriginalFilename();
	                if (!zalacznik.equals("")) {
	 
	                    messageHelper.addAttachment(nazwaZalacznika, new InputStreamSource() {
	                         
	                        @Override
	                        public InputStream getInputStream() throws IOException {
	                            return zalacznik.getInputStream();
	                        }
	                    });
	                }
	                 
	            }
	 
	        });
         
        return "eMailSuccess";
    }
}